package com.nakamachizu.controller;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.nakamachizu.model.MapData;
import com.nakamachizu.service.MapDataService;
import com.nakamachizu.util.ForwardUtil;

public class LoginController extends Controller {

    @Override
    public Navigation run() {
        
        UserService userService = UserServiceFactory.getUserService();
        
        User user = userService.getCurrentUser();
        if(user == null){
            return redirect(userService.createLoginURL(request.getRequestURI()));
            //response.sendRedirect(userService.createLoginURL(request.getRequestURI()));

        }else{
            MapDataService mds = new MapDataService();
            MapData map = mds.getMapData(user.getEmail());
            if(map != null){
                requestScope("mapKey", map.getAccessKey());
                requestScope("expireDate", map.getExpire());
            }
            
            String logoutUrl = userService.createLogoutURL("/");
            requestScope("logoutUrl", logoutUrl);
            requestScope("email", user.getEmail());
            requestScope("nickName", user.getNickname());
        }
        
        return forward(ForwardUtil.forwardJsp("login.jsp"));
    }
}
